class_name ItemIcon
extends Panel
@onready var item_icon: TextureRect = %item_icon
@onready var item_name: Label = %item_name
@onready var item_type: RichTextLabel = %item_type
@onready var description: RichTextLabel = $"%description"
@export var player_stats: PandoraEntity
@onready var buy_button: Button = %BuyButton
@export var item_stats: PandoraEntity : set = _set_item_stats
var cost = 0


signal buy_item

func _ready() -> void:
	player_stats = Utils.player.player_stats
	EventBus.subscribe("add_item_result", on_add_item_result)

func on_add_item_result(result: bool, _name: String):
	if _name != self.name:
		return
	if result:
		player_stats.set_integer("gold", player_stats.get_integer("gold") - item_stats.get_integer("cost"))
		player_stats.get_array("player_item_list").append(item_stats)
		buy_item.emit()
		print("购买成功")
		for child in self.get_children():
			child.queue_free()

func _on_animated_button_pressed() -> void:
	EventBus.push_event("add_item", [item_stats, name])

## 初始化装备信息
func _set_item_stats(value: PandoraEntity) -> void:
	if value == null:
		return
	if not is_node_ready():
		await ready
	self.size_flags_horizontal = Control.SIZE_EXPAND_FILL
	item_icon.texture = value.get_resource("item_texture")
	item_name.text = value.get_string("item_name")
	description.text = ItemManager.get_item_info(value)
	cost = value.get_integer("cost")
	buy_button.text = "购买(%s金币)" % [cost]
	item_stats = value

func _on_tree_exited() -> void:
	EventBus.unsubscribe("add_item_result", on_add_item_result)
